#include <stdio.h>
#include "kernel_list.h"
#include <stdlib.h>
struct node // 大结构体 【用户数据】
{
    int value;

    // 标准链表
    struct list_head list; // 小结构体 【链表的指针数据】
};

struct node *create_node(int value)
{
    struct node *node = malloc(sizeof(struct node));
    node->value = value;
    return node;
}
int main()
{

    // 申请头节点
    struct node *head = malloc(sizeof(struct node));

    // 初始化
    INIT_LIST_HEAD(&head->list);

    printf("%d\n", &((struct node *)0)->list);

    printf("head %p\n", head);
    printf("&(head->list) %p\n", &head->list);
    printf("list_entry(&head->list, struct node, list) %p\n", list_entry(&head->list, struct node, list));

    // 申请新的节点
    // struct node *n1 = malloc(sizeof(struct node));
    // n1->value = 11;
    struct node *n1 = create_node(11);
    struct node *n2 = create_node(22);
    struct node *n3 = create_node(33);
    struct node *n4 = create_node(44);
    struct node *n5 = create_node(55);
    struct node *n6 = create_node(66);

    // 尾部插入
    list_add_tail(&n1->list, &head->list);
    list_add_tail(&n2->list, &head->list);
    list_add_tail(&n3->list, &head->list);
    list_add_tail(&n4->list, &head->list);
    list_add_tail(&n5->list, &head->list);
    list_add_tail(&n6->list, &head->list);

    /*     // 遍历链表
        // 遍历小结构体
        struct list_head *pos1;
        list_for_each(pos1, &head->list)
        {
            printf("%p\n", pos1);                                 // 小结构体的地址
            printf("%p \n", list_entry(pos1, struct node, list)); // 大结构体的地址
            printf("%d\n", list_entry(pos1, struct node, list)->value);
        }

        printf("---------------------------------------------------\n");
        // 遍历大结构体 list_for_each_entry 读取大结构体 pos  相当于加了list_entry
        struct node *pos;
        list_for_each_entry(pos, &head->list, list)
        {
            printf("value: %d\n", pos->value);
        }

        // 剔除节点
        list_del(&n2->list);

        printf("---------------------------------------------------\n");
        // 遍历大结构体 list_for_each_entry 读取大结构体 pos  相当于加了list_entry
        struct node *pos2;
        list_for_each_entry(pos2, &head->list, list)
        {
            printf("value: %d\n", pos2->value);
        }
     */
    // 遍历
    printf("--------遍历-------------------------------------------\n");
    struct node *pos2;
    list_for_each_entry(pos2, &head->list, list)
    {
        printf("value: %d\n", pos2->value);
    }

    printf("--------遍历删除偶数-------------------------------------------\n");
    struct node *pos;
    struct node *n;
    list_for_each_entry_safe(pos, n, &head->list, list)
    {
        if (pos->value % 2 == 0)
        {
            list_del(&pos->list);
        }
    }
    printf("--------遍历-------------------------------------------\n");
    // 遍历
    struct node *pos1;
    list_for_each_entry(pos1, &head->list, list)
    {
        printf("value: %d\n", pos1->value);
    }
    return 0;
}
